package com.czy.owner.ui.archive;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.GarageSelectCarAdapter;
import com.czy.owner.api.CarsListApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.IllegalQueryDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.IllegalEvent;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.garage.PickBrandActivity;
import com.czy.owner.ui.illegalquery.IllegalQueryActivity;
import com.czy.owner.ui.illegalquery.IllegalQueryDetailActivity;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hedepu on 2017/9/25.
 * 选择查询车辆
 */
public class SelectIllegalQueryActivity extends BaseActivity implements OnRefreshListener {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.refresh_target)
    RecyclerView refreshTarget;
    @BindView(R.id.tv_add_car)
    ImageView imgAddCar;
    @BindView(R.id.tv_temp_query)
    ImageView imgTempQuery;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    @BindView(R.id.ll_garage_none)
    LinearLayout llGarageNone;

    private GarageSelectCarAdapter mAdapter;
    private DiskLruCacheHelper cacheHelper;
    private List<CarInfo> list = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_select_illegal_query;
    }

    @Override
    protected void initInjector() {
          /*註冊*/
        RxBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("选择查询车辆");
        try {
            cacheHelper = new DiskLruCacheHelper(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        swipeToLoadLayout.setOnRefreshListener(this);

    }

    @Override
    protected void updateViews() {
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        if (UserHelper.getInstance().getCarInfoList() != null && UserHelper.getInstance().getCarInfoList().size() > 0) {
            list.addAll(UserHelper.getInstance().getCarInfoList());
        }
        mAdapter = new GarageSelectCarAdapter(this, list);
        setAdapterData(list);
        refreshTarget.setLayoutManager(layoutManager);
        refreshTarget.setAdapter(mAdapter);
        refreshTarget.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object o, View view) {
                if (StringUtils.isEmpty(mAdapter.data.get(position).getChassisNumber()) && StringUtils.isEmpty(mAdapter.data.get(position).getEngineType())) {
                    startActivity(new Intent(SelectIllegalQueryActivity.this, IllegalQueryActivity.class).putExtra("carInfo", mAdapter.data.get(position)).putExtra("isGarage", true));
                } else {
                    illegalCity(mAdapter.data.get(position));
                }

            }
        });

        swipeToLoadLayout.setRefreshing(true);
    }

    /*接受事件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(IllegalEvent changeText) {
        if ("2".equals(changeText.getType())) {
            finish();
        } else if ("3".equals(changeText.getType())) {
            onRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
                  /*註冊*/
        RxBus.getDefault().unRegister(this);
    }

    //    frameno和engineno 根据管局需要输入（100为全部输入，0为不输入）
//    车牌号：91k56
//    车架号：084527
//    发动机号：562189
//    获取交管局参数
    private void illegalCity(final CarInfo carInfo) {
        //当车牌号信息被修改时提示是否隐藏
        mLoadView.ShowLoadView();
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.PUB_ILLEGALCITY);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(SelectIllegalQueryActivity.this).getSession());
        params.addBodyParameter("lsprefix", carInfo.getLicenseNumber().substring(0, 1));
        params.addBodyParameter("lsnum", carInfo.getLicenseNumber().substring(1, 2));
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(SelectIllegalQueryActivity.this, result);
                int frameno = -1;
                int engineno = -1;
                String carorg;
                if (data != null) {
                    frameno = JsonUtil.getJsonValuesInt(data, "frameno");
                    engineno = JsonUtil.getJsonValuesInt(data, "engineno");
                    carorg = JsonUtil.getJsonValuesString(data, "carorg");
                    if (frameno > 0 && StringUtils.isEmpty(carInfo.getChassisNumber())) {
                        startActivity(new Intent(SelectIllegalQueryActivity.this, IllegalQueryActivity.class).putExtra("carInfo", carInfo).putExtra("isGarage", true));
                        Log.i("hedepu", "frameno null");
                        mLoadView.CancleLoadView();
                        return;
                    }
                    if (engineno > 0 && StringUtils.isEmpty(carInfo.getEngineType())) {
                        startActivity(new Intent(SelectIllegalQueryActivity.this, IllegalQueryActivity.class).putExtra("carInfo", carInfo).putExtra("isGarage", true));
                        Log.i("hedepu", "engineno null");

                        mLoadView.CancleLoadView();

                        return;
                    }
                    if (frameno > 0 && frameno != 100 && carInfo.getChassisNumber().length() < frameno) {
                        PhoneUtils.ShowToastMessage(SelectIllegalQueryActivity.this, "保存的车架号最少需要后" + frameno + "位");
                        mLoadView.CancleLoadView();
                        return;
                    }
                    if (engineno > 0 && engineno != 100 && carInfo.getEngineType().length() < engineno) {
                        PhoneUtils.ShowToastMessage(SelectIllegalQueryActivity.this, "保存的发动机号最少需要后" + engineno + "位");
                        mLoadView.CancleLoadView();
                        return;
                    }
                    getQueryLLLegalList(carInfo.getLicenseNumber().substring(0, 1), carInfo.getLicenseNumber().substring(1, carInfo.getLicenseNumber().length()), carorg, carInfo.getEngineType().substring(engineno == 100 ? 0 : carInfo.getEngineType().length() - engineno, carInfo.getEngineType().length()),
                            carInfo.getChassisNumber().substring(frameno == 100 ? 0 : carInfo.getChassisNumber().length() - frameno, carInfo.getChassisNumber().length())

                    );
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
                startActivity(new Intent(SelectIllegalQueryActivity.this, IllegalQueryActivity.class).putExtra("carInfo", carInfo).putExtra("isGarage", true));

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void getQueryLLLegalList(String lsprefix, String lsnum, String carorg, String engineno, String frameno) {

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.PUB_QUERYLLLEGAL);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(SelectIllegalQueryActivity.this).getSession());
        params.addBodyParameter("lsprefix", lsprefix);
        params.addBodyParameter("lsnum", lsnum);
        params.addBodyParameter("carorg", carorg);
        params.addBodyParameter("engineno", engineno);
        params.addBodyParameter("frameno", frameno);
        params.addBodyParameter("isTemporary", String.valueOf(false));
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (flag) {
                    String mData = JsonUtil.getJsonValuesString(result, "data");
                    List<IllegalQueryDetailModel> list = new ArrayList<>();
                    list.clear();
                    list = GsonUtils.fromJsonList(mData, IllegalQueryDetailModel.class);
                    Intent ti = new Intent(SelectIllegalQueryActivity.this, IllegalQueryDetailActivity.class);
                    ti.putExtra("list", (Serializable) list);
                    startActivity(ti);
                } else {
                    PhoneUtils.ShowToastMessage(SelectIllegalQueryActivity.this, exp);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    public void setAdapterData(List<CarInfo> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isDefault()) {
                CarInfo carInfo = list.get(i);
                list.remove(i);
                list.add(0, carInfo);
                break;
            }
        }
        mAdapter.setList(list);
        if (mAdapter.data.size() == 0) {
            llGarageNone.setVisibility(View.VISIBLE);
            refreshTarget.setVisibility(View.GONE);
        } else {
            llGarageNone.setVisibility(View.GONE);
            if (refreshTarget.getVisibility() == View.GONE)
                refreshTarget.setVisibility(View.VISIBLE);
        }

    }


    //获取车库信息
    private void getDataList() {

        CarsListApi carsListApi = new CarsListApi(new HttpOnNextListener<List<CarInfo>>() {
            @Override
            public void onNext(List<CarInfo> model) {

                if (model != null && model.size() != 0) {
                    UserHelper.getInstance().getCarInfoList().clear();
                    UserHelper.getInstance().setCarInfoList(model);
                    setAdapterData(model);
                }
                swipeToLoadLayout.setRefreshing(false);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                swipeToLoadLayout.setRefreshing(false);

            }
        }, this);
        carsListApi.setSession(UserHelper.getInstance().

                getSessionInfoModel(this).

                getSession());
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(carsListApi);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Constants.ACTIVITY_RESULT_CODE_CAR_ADD) {
            swipeToLoadLayout.setRefreshing(true);

        }
    }

    @OnClick({R.id.tv_add_car, R.id.tv_temp_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add_car:
                Intent intent = new Intent();
                intent.setClass(this, PickBrandActivity.class);
                // 新增车辆无需立即返回
                intent.putExtra(PickBrandActivity.START_FLAG, 0);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_temp_query:
                startActivity(new Intent(this, IllegalQueryActivity.class));
                break;
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(SelectIllegalQueryActivity.this)) {
                    PhoneUtils.ShowToastMessage(SelectIllegalQueryActivity.this, "网络连接错误");
                    return;
                }
                getDataList();
            }
        }, 500);

    }
}
